package com.shadow.bus.main.alarm;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.shadow.bus.config.ServiceUrl;
import com.shadow.bus.config.SpKey;
import com.shadow.bus.entity.AlarmInfoEntity;
import com.shadow.bus.entity.AlarmTypeEntity;
import com.shadow.bus.main.MainPagerAdapter;
import com.tepth.shadow.ui.dialog.sweet.DialogDelegate;
import com.tepth.shadow.ui.dialog.sweet.SweetAlertDialogDelegate;
import com.zhangyu.shadow.core.delegate.RxShadowDelegate;
import com.zhangyu.shadow.core.net.callback.IError;
import com.zhangyu.shadow.core.net.callback.ISuccess;
import com.zhangyu.shadow.core.net.rx.RxRestClient;
import com.zhangyu.shadow.core.util.storage.ShadowPreference;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;

import busfix.tepth.com.shadow_bus.R;
import busfix.tepth.com.shadow_bus.R2;
import butterknife.BindView;

/**
 * @author zhangyu
 * @date 2018/7/10
 */

public class AlarmDelegate extends RxShadowDelegate {
    private static final String BUS_CODE = "busCode";
    private static final String BUS_ID = "busId";
    private String mBusCode;
    private long mBusId;

    public static AlarmDelegate newInstance(long id, String code) {
        Bundle args = new Bundle();
        args.putString(BUS_CODE, code);
        args.putLong(BUS_ID, id);
        AlarmDelegate fragment = new AlarmDelegate();
        fragment.setArguments(args);
        return fragment;
    }

    @BindView(R2.id.toolbar)
    Toolbar mToolbar;
    @BindView(R2.id.viewpager)
    ViewPager mViewPager;
    @BindView(R2.id.tabs)
    TabLayout mTabLayout;
    private List<Fragment> mDelegates = new ArrayList<>();
    private DialogDelegate mDialogDelegate;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        setRetainInstance(true);
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle != null) {
            mBusCode = bundle.getString(BUS_CODE);
            mBusId = bundle.getLong(BUS_ID);
        }
    }

    @Override
    public Object setLayout() {
        return R.layout.delegate_alarm;
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, View rootView) {
        mToolbar.setNavigationIcon(R.drawable.ic_arrow_back_white_24dp);
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pop();
            }
        });
        mToolbar.setTitle("车辆编号:" + mBusCode + "报警信息");
        mDialogDelegate = new SweetAlertDialogDelegate(getContext());
    }

    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);
        requestData();
    }

    private void requestData() {
        mDialogDelegate.showProgressDialog(true, "正在加载...");
        mDisposables.add(RxRestClient.builder()
                .url(ServiceUrl.ALARM_INFO)
                .params("authKey", ShadowPreference.getCustomAppProfile(SpKey.TOKEN))
                .params("vehicleId", mBusId)
                .success(new ISuccess() {
                    @Override
                    public void onSuccess(String response) {
                        new AlarmDataConverter().converter(response, new AlarmDataConverter.OnDataConverterListener() {
                            @Override
                            public void onConverter(ArrayList<AlarmTypeEntity> list) {
                                setUpTabs(list);
                                if (mDialogDelegate != null) {
                                    mDialogDelegate.clearDialog();
                                }
                            }
                        });
                    }
                })
                .error(new IError() {
                    @Override
                    public void onError(int code, String msg) {
                        mDialogDelegate.stopProgressWithFailed("加载失败", msg);
                    }
                })
                .build()
                .get());
    }

    private void setUpTabs(ArrayList<AlarmTypeEntity> list) {
        try {
            //页面，数据源
            List<View> tabViews = new ArrayList<>();
            for (AlarmTypeEntity alarmType : list) {
                ArrayList<AlarmInfoEntity> alarmInfo = alarmType.getListAlarm();
                mDelegates.add(TabFragment.newInstance(alarmInfo));
                View v = LayoutInflater.from(getContext()).inflate(R.layout.view_tab_alarm, null);
                TextView tvName = v.findViewById(R.id.tv_name);
                String level = null;
                switch ((int) alarmType.getLevel()) {
                    case 1:
                        level = "一级报警";
                        break;
                    case 2:
                        level = "二级报警";
                        break;
                    case 3:
                        level = "三级报警";
                        break;
                }
                tvName.setText(level);
                TextView textView = v.findViewById(R.id.tv_count);
                textView.setText(
                        MessageFormat.format("({0})", alarmInfo.size()));
                tabViews.add(v);
            }


            MainPagerAdapter pagerAdapter = new MainPagerAdapter(getChildFragmentManager(), mDelegates);
            mViewPager.setAdapter(pagerAdapter);
            mTabLayout.setupWithViewPager(mViewPager);

            //设置自定义视图
            for (int i = 0; i < mTabLayout.getTabCount(); i++) {
                TabLayout.Tab tab = mTabLayout.getTabAt(i);
                if (tab != null) {
                    tab.setCustomView(tabViews.get(i));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(getContext(), "没有相关报警数据!", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public boolean onBackPressedSupport() {
        pop();
        return true;
    }
}
